package com.note.copy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author RenGaoshuai
 * @date 2024/4/15 15:15
 * @description 浅拷贝
 * 将需要北拷贝的对象在堆内存中赋值一份。
 * 如果北拷贝的对象存在引用类型属性，那么此引用类型属性不会被拷贝。
 * 详细看下面的示例
 */
public class CopyTest1 {


    public static void main(String[] args) throws Exception {
        Source source1 = new Source("测试分数", 120L);
        Student s1 = new Student(12, "张三", source1);

        Student s2 = (Student) s1.clone();

        System.out.println("------------clone()----------------");
        System.out.println(s1 == s2);//false  s2是拷贝s1的，因此两个地址不一样
        System.out.println(s1.getSource() == s2.getSource());//共用的原来的

        System.out.println("------------hutool BeanCopy----------------");
        Student s3 = BeanUtil.copyProperties(s1, Student.class);
        System.out.println(s1 == s3);//false  s2是拷贝s1的，因此两个地址不一样
        System.out.println(s1.getSource() == s3.getSource());//共用的原来的

        System.out.println("------------ObjectUtil.clone----------------");
        Student s4 = ObjectUtil.clone(s1);
        System.out.println(s1 == s4);//false  s2是拷贝s1的，因此两个地址不一样
        System.out.println(s1.getSource() == s4.getSource());//共用的原来的

        System.out.println("------------ObjectUtil.cloneByStream----------------");
        Student s5 = ObjectUtil.cloneByStream(s1);
        System.out.println(s1 == s5);//false  s2是拷贝s1的，因此两个地址不一样
        System.out.println(s1.getSource() == s5.getSource());//共用的原来的

    }
}

@Data
@AllArgsConstructor
class Student implements Serializable,Cloneable {

    private Integer age;
    private String name;
    private Source source;

    @Override
    protected Object clone() {
        Student p = null;
        try {
            p = (Student) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return p;
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Source implements Serializable,Cloneable {

    private String sourceName;
    private Long sourceType;

    @Override
    protected Object clone() {
        Source p = null;
        try {
            p = (Source) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return p;
    }
}

